<?php
/**
 * Common
 * 
 * @author ShuangYa
 * @package Example
 * @category Controller
 * @link https://www.sylingd.com/
 * @copyright Copyright (c) 2019 ShuangYa
 */
namespace App\Module\Device\Controller;

use App\Library\Utils;
use App\Model\Device;
use App\Service\Command;
use Sy\ControllerAbstract;
use Sy\Http\Request;

class Common extends ControllerAbstract {
	private $device;
	private $command;

	public function __construct(Device $device, Command $command) {
		$this->device = $device;
		$this->command = $command;
	}

	public function heartbeatAction(Request $request) {
		$id = $request->get['id'];
		$ph = $request->get['ph'];
		$temp = $request->get['temp'];

		$data = [
			'device_id' => $id,
			'status' => 'online',
			'last_heartbeat_time' => date('Y-m-d H:i:s'),
			'ph' => $ph,
			'temperature' => $temp,
		];

		// 查询是否有数据
		$has = $this->device->get($id);
		if ($has) {
			$this->device->set($data, $id);
		} else {
			$this->device->add($data);
		}

		// 查询是否有待执行的命令
		$command = $this->command->list([
			'device_id' => $id,
			'status' => Command::STATUS_PENDING
		]);
		if (count($command) > 0) {
			// 更改状态为execute
			// 写简单点，暂时不考虑并发运行
			$this->command->getModel()->set([
				'status' => Command::STATUS_EXECUTE
			], [
				'status' => Command::STATUS_PENDING
			]);
			$res = join("\n", array_map(function ($item) {
				return "{$item['command_id']},{$item['command']},{$item['param']}";
			}, $command));
		} else {
			$res = 'no_command';
		}
		
		$res = Utils::getMachineResult($res);
		header('Content-Length: ' . strlen($res));
		return $res;
	}
}